package com.shidaimanong.controller;

import com.shidaimanong.entity.User;
import com.shidaimanong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 学编程，关注：十代码农
 * 抖音、快手、B站、西瓜视频、今日头条
 */
@Controller
@RequestMapping("/user")
public class UserWebController {

    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public String index() {
        return "index"; //当浏览器输入/index时，会返回 /templates/index时.html页面
    }

    @GetMapping("/list")
    public ModelAndView userList() {
        ModelAndView modelAndView = new ModelAndView("userList");
        modelAndView.addObject("users", userService.queryAllUsers());
        return modelAndView;
    }

    @GetMapping("/addUserPage")
    public ModelAndView addUserPage() {
        ModelAndView modelAndView = new ModelAndView("addUserPage");
        return modelAndView;
    }

    @PostMapping(value = "addUser")
    public ModelAndView addUser(int id, String userName) {
        userService.addUser(id, userName);
        return new ModelAndView("redirect:/user/list");
    }

    @GetMapping(value = "modifyUserPage/{id}")
    public ModelAndView modifyUserPage(@PathVariable int id) {
        User user = userService.queryUser(id);
        ModelAndView modelAndView = new ModelAndView("modifyUserPage");
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @PostMapping(value = "modifyUser")
    public ModelAndView modifyUser(int id, String userName) {
        userService.modifyUser(id, userName);
        return new ModelAndView("redirect:/user/list");
    }
}